const {v4: uuidv4} = require('uuid')
const Notes = require('../../models/notes')

const getNotesHandler = async (_, res) => {
  try {
    const notesList = await Notes.find()
    // notesList.length
    res.status(200).json(notesList)
    // : res.status(404).json({success: false, msg: 'Документы не найдены'})
  } catch (e) {
    res.status(500).json({success: false, msg: e})
  }
}

const postNewNoteHandler = async (req, res) => {
  const {text, title} = req.body
  try {
    const result = await Notes.create({
      id: uuidv4(),
      text,
      title,
    })
    res.status(200).json(result)
  } catch (e) {
    res.status(500).json({success: false, msg: e})
  }
}

const deleteNoteHandler = async (req, res) => {
  const {id} = req.params
  try {
    const deletedNote = await Notes.findOneAndDelete({id})
    if (deletedNote) {
      res.status(200).json({success: true, msg: 'Заметка успешно удалена'})
    } else {
      res.status(404).json({success: false, msg: 'Заметка не найдена'})
    }
  } catch (e) {
    res.status(500).json({success: false, msg: e})
  }
}

module.exports = {getNotesHandler, postNewNoteHandler, deleteNoteHandler}
